﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Stick : Unit
{
    public float Length = 1;

    float hw {  get { return 0.1f; } }
    float hh { get { return Length / 2; } }

    public float AngularDelta { get; private set; }

    protected override void Sync()
    {
        base.Sync();
        BeginSync();
        SyncFloat(ref Length);
        EndSync();
    }

    public override Vector2 PositionOffset(float angle)
    {
        var r = GetRadius(angle - Angle);
        return new Vector2(Mathf.Cos(angle) * r, Mathf.Sin(angle) * r);
    }

    public float GetRadius(float angle)
    {
        angle = MathEx.RangeInPi2(angle);
        var ca = MathEx.Arc(hw, hh);
        var r = hh;
        if (angle <= ca)
            return 0;
        else if (angle <= Mathf.PI - ca)
            return r;
        else if (angle <= Mathf.PI)
            return 0;
        else if (angle <= Mathf.PI + ca)
            return 0;
        else if (angle <= Mathf.PI * 2 - ca)
            return r;
        else
            return 0;
    }

    public override void UpdateSelf(float te, ConnectionType ct)
    {
        if (Src == null)
            return;

        var arcFromSrc = 0f;
        if ((ct & ConnectionType.OnTopFixX) > 0)
            arcFromSrc = Mathf.PI / 2;
        else if ((ct & ConnectionType.OnBottomFixX) > 0)
            arcFromSrc = Mathf.PI * 3 / 2;
        else if ((ct & ConnectionType.OnLeftFixY) > 0)
            arcFromSrc = Mathf.PI;
        else
            arcFromSrc = 0f;

        var arcToSrc = Mathf.PI + arcFromSrc;

        if (ct == ConnectionType.Concentric)
        {
            AngularDelta = (Src as IAngularVelocityDeliever).AngularDelta;
            Angle += AngularDelta;
            Pos = Src.Pos;
        }
        else if ((ct & ConnectionType.Clenching) > 0)
        {
            Pos = Src.Pos + Src.PositionOffset(arcFromSrc) - PositionOffset(arcToSrc);
        }
    }
}
